package com.hz.pay.center.utils;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.*;
import com.alipay.api.response.*;
import com.hz.pay.center.config.PayCenterConfig;
import com.hz.pay.center.exception.BizException;
import com.hz.pay.center.service.strategy.impl.AliapyQrCodeStrategyPayServiceImpl;
import com.hz.pay.center.vo.PayVo;
import com.pay.common.resp.PayNotifyData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;

/**
 * 调用支付宝的接口
 */
@Component
public class AlipayUtils {

    private Logger logger = LoggerFactory.getLogger(AlipayUtils.class);


    @Autowired
    private PayCenterConfig payCenterConfig;


    /**
     * alipay.trade.precreate(统一收单线下交易预创建)  扫码支付
     * @param payVo
     * @return
     * @throws BizException
     */
    public String alipayQrCodePay(PayVo payVo) throws BizException {
        logger.info("#######正在执行支付宝的扫码支付接口###########");

        if (StringUtils.isEmpty(payVo.getOutTradeNo())){
            throw new BizException("outTradeNo不能为空");
        }


        if (StringUtils.isEmpty(payVo.getTotalAmount())){
            throw new BizException("totalAmount不能为空");
        }


        if (StringUtils.isEmpty(payVo.getSubject())){
            throw new BizException("subject不能为空");
        }


        AlipayClient alipayClient = new DefaultAlipayClient(payCenterConfig.getUrl(), payCenterConfig.getAppId(),
                payCenterConfig.getPrivateKey(),payCenterConfig.getFormat(), payCenterConfig.getCharSet(),
                payCenterConfig.getAlipayPubKey(),payCenterConfig.getSignType());

        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();

        /**
         * 支付完成后的回调
         */
        request.setNotifyUrl(payCenterConfig.getNotifyUrl());
        /**
         * 支付成功后跳转的页面
         */
        request.setReturnUrl("https://www.baidu.com");

        JSONObject bizData = new JSONObject();
        bizData.put("out_trade_no",payVo.getOutTradeNo());
        bizData.put("total_amount", payVo.getTotalAmount());
        bizData.put("subject", payVo.getSubject());

        request.setBizContent(bizData.toJSONString());

        AlipayTradePrecreateResponse response = null;

        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            logger.error("AlipayApiException",e);
            //TODO
        }

        String qRCode = response.getQrCode();

        return qRCode;

    }


    /***
     * alipay.trade.app.pay(app支付接口2.0)
     */
    public void  alipayAppPay(){

        //对接支付宝的扫码支付接口

    }

    /**
     * 支付宝alipay.trade.page.pay(统一收单下单并支付页面接口)
     * @param payVo
     */
    public String alipayPapePay(PayVo payVo){

        logger.info("#######正在执行支付宝的PC端支付接口###########");

        if (StringUtils.isEmpty(payVo.getOutTradeNo())){
            throw new BizException("outTradeNo不能为空");
        }


        if (StringUtils.isEmpty(payVo.getTotalAmount())){
            throw new BizException("totalAmount不能为空");
        }


        if (StringUtils.isEmpty(payVo.getSubject())){
            throw new BizException("subject不能为空");
        }


        AlipayClient alipayClient = new DefaultAlipayClient(payCenterConfig.getUrl(), payCenterConfig.getAppId(),
                payCenterConfig.getPrivateKey(),payCenterConfig.getFormat(), payCenterConfig.getCharSet(),
                payCenterConfig.getAlipayPubKey(),payCenterConfig.getSignType());


        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();

        /**
         * 支付成功后跳转的页面
         */
        request.setReturnUrl("https://www.baidu.com");

        /**
         * 支付完成后的回调
         */
        request.setNotifyUrl(payCenterConfig.getNotifyUrl());

        JSONObject bizData = new JSONObject();

        bizData.put("out_trade_no",payVo.getOutTradeNo());
        bizData.put("product_code","FAST_INSTANT_TRADE_PAY");
        bizData.put("total_amount", payVo.getTotalAmount());
        bizData.put("subject", payVo.getSubject());

        request.setBizContent(bizData.toJSONString());

        try {
            AlipayTradePagePayResponse response = alipayClient.pageExecute(request);

           String payUrl = response.getBody();

            logger.info("payURL : {}",payUrl);


           return payUrl;

        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 支付宝支付结果查询
     * @param paySerialNo
     * @return
     * @throws AlipayApiException
     */
    public AlipayTradeQueryResponse alipayTradeQuery(String paySerialNo) throws AlipayApiException {

        AlipayClient alipayClient = new DefaultAlipayClient(payCenterConfig.getUrl(), payCenterConfig.getAppId(),
                payCenterConfig.getPrivateKey(),payCenterConfig.getFormat(), payCenterConfig.getCharSet(),
                payCenterConfig.getAlipayPubKey(),payCenterConfig.getSignType());

        AlipayTradeQueryRequest tradeQueryRequest = new AlipayTradeQueryRequest();

        JSONObject jsonObject = new JSONObject();

        jsonObject.put("out_trade_no",paySerialNo);

        tradeQueryRequest.setBizContent(jsonObject.toJSONString());

        AlipayTradeQueryResponse alipayTradeQueryResponse = alipayClient.execute(tradeQueryRequest);

//        if (!"10000".equals(response.getCode())){
//
//           String msg = response.getMsg();
//
//            return null;
//        }
//
//        PayNotifyData payNotifyData = new PayNotifyData();
//        payNotifyData.setTradeStatus(response.getTradeStatus());
//        //TODO

        return alipayTradeQueryResponse;


    }

    /**
     * 关闭支付宝的交易
     */
    public AlipayTradeCloseResponse  alipayTradeClose(String paySerialNo,String bankRespNo) throws AlipayApiException {


        AlipayClient alipayClient = new DefaultAlipayClient(payCenterConfig.getUrl(), payCenterConfig.getAppId(),
                payCenterConfig.getPrivateKey(),payCenterConfig.getFormat(), payCenterConfig.getCharSet(),
                payCenterConfig.getAlipayPubKey(),payCenterConfig.getSignType());

        AlipayTradeCloseRequest closeRequest = new AlipayTradeCloseRequest();

        JSONObject object = new JSONObject();

        object.put("out_trade_no",paySerialNo);
        object.put("trade_no",bankRespNo);

        closeRequest.setBizContent(object.toJSONString());


        AlipayTradeCloseResponse response = alipayClient.execute(closeRequest);

        return response;

    }

    /**
     *
     * @param paySerialNo
     * @param refundAmt
     * @param reason
     * @param refundSeirlNo
     */
    public AlipayTradeRefundResponse alipayTradeRefund(String paySerialNo, BigDecimal refundAmt, String reason, String refundSeirlNo) throws AlipayApiException {

        //实现支付宝的接口


        AlipayClient alipayClient = new DefaultAlipayClient(payCenterConfig.getUrl(), payCenterConfig.getAppId(),
                payCenterConfig.getPrivateKey(),payCenterConfig.getFormat(), payCenterConfig.getCharSet(),
                payCenterConfig.getAlipayPubKey(),payCenterConfig.getSignType());

        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();

        JSONObject jsonObject = new JSONObject();

        jsonObject.put("out_trade_no",paySerialNo);
        jsonObject.put("refund_amount",refundAmt);
        jsonObject.put("refund_reason",reason);
        jsonObject.put("out_request_no",refundSeirlNo);

        request.setBizContent(jsonObject.toJSONString());

        AlipayTradeRefundResponse response = alipayClient.execute(request);

        return response;



    }


}
